// 编辑器
var um = UM.getEditor('myEditor');

$(".steps-starting-step").steps({
    headerTag: "h6",
    bodyTag: "fieldset",
    titleTemplate: '<span class="number">#index#</span> #title#',
    labels: {
        previous: '上一步',
        next: '下一步',
        finish: '完  成'
    },
    autoFocus: true,
    onFinished: function (event, currentIndex) {
        if ($('#coverPic').val() == ''){
            swal("请设置产品封面", "", "error");
            return false;
        }
        window.location.href = contextpath + "product/";
    },
    onStepChanging: function (event, currentIndex, newIndex) {
        if (currentIndex != 0 || newIndex != 1) {
            return true;
        }

        $('#description').val(um.getContent());
        if ($('#description').val() == ''){
            swal("请设置产品描述", "", "warning");
            return false;
        }

        // 表单校验
        if ($("#infoForm").valid()) {
            $.ajax({
                url: contextpath + "product/save",
                type: "POST",
                data: $("#infoForm").serialize(),
                dataType: "json",
                cache: false,
                async: false,
                success: function(data) {
                    $("#id").val(data); //返回id
                    initFileInput();
                    return true;
                }
            });

            return true;
        }

        return false;
    }
});

function initFileInput(){
    $("#input-id").fileinput('destroy');

    $("#input-id").fileinput({
        language: 'zh', //设置语言
        uploadClass: 'btn btn-success',
        uploadUrl: contextpath + "upload/add/product/" + $("#id").val(),
        allowedFileTypes: ['image'],
        allowedFileExtensions: ['jpg', 'png'],//接收的文件后缀
        maxFileSize: 10000, // 单位kb
        maxFileCount: 10,
    }).off('fileuploaded').on('fileuploaded', function(event, data, previewId, index) {
        appendImage(data.response, false);

        return;
    });
}

// 根据数组数据，生成图片
function appendImage(dataArr, clear){
    if (clear){
        $("#imageContainer").empty();
    }

    var coverPic = $('#coverPic').val();
    for(var i = 0; i < dataArr.length; i++){
        var data = dataArr[i];
        var src = contextpath + data.url;
        $("#imageContainer").append($("#imageDiv").html().setTokens({'src': src, 'name': data.fileName, 'desc': data.description, 'id': data.id, 'sort': data.sort, 'hideCover': coverPic == data.id? "hide":""}))
    }

    // 监听image设置封面
    $('.image-cover').click(function () {
        var $div = $(this).closest(".image-div");
        swal({
            title: "设置封面",
            text: "确定将图片 <span class='text-danger text-size-large text-bold'>" + $div.attr("data-name") + "</span> 设为封面 ?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            html: true
        }, function () {
            $.get(contextpath + "product/setCoverPic/" + $("#id").val() + "?picId=" + $div.attr("data-id"),
                function (d) {
                    $('#coverPic').val(d);

                    swal("设置成功", "", "success");
                    $.get(contextpath + "upload/get/product/" + $("#id").val(), function (data) {
                        appendImage(data, true)
                    });
                })
        });
    });

    // 监听image设置banner
    $('.image-banner').click(function () {
        var $div = $(this).closest(".image-div");
        swal({
            title: "设置banner广告",
            text: "确定将图片 <span class='text-danger text-size-large text-bold'>" + $div.attr("data-name") + "</span> 设为banner广告 ?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            html: true
        }, function () {
            $.get(contextpath + "banner/set/1?refId=" + $("#id").val() + "&imageId=" + $div.attr("data-id"),
                function () {
                    swal("设置banner广告成功", "", "success");
                })
        });
    });

    // 监听image删除
    $('.image-del').click(function () {
        var $div = $(this).closest(".image-div");
        swal({
            title: "删除",
            text: "确定要删除图片 " + $div.attr("data-name") + " ?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            $.get(contextpath + "upload/delete/" + $div.attr("data-id"),
                function (d) {
                    swal("删除成功", "", "success");

                    // 删除div
                    $div.remove();
                })
        });
    });

    // 监听image编辑
    $('.image-edit').click(function () {
        var $div = $(this).closest(".image-div");
        $("#edit").validate().resetForm();
        $('#edit').fill({'id': $div.attr('data-id'), 'fileName': $div.attr('data-name'), 'sort': $div.attr('data-sort'), 'description': $div.attr('data-desc')});

        $('#edit_dialog').modal('show');
    });
}

$(function () {

    $('.select').select2({
        minimumResultsForSearch: Infinity
    });

    // $(".switch").bootstrapSwitch({onSwitchChange:function (event, state) {
    //     $('input[name="'+$(this).data('name')+'"]').val(state);
    // }});

    $('[data-popup="lightbox"]').fancybox({
        padding: 3
    });

    // 点击添加图片按钮
    $("#addImageBtn").click(function () {
        $("#uploadImageModal").modal("show");
    });

    $('#uploadImageModal').on('hidden.bs.modal', function () {
        $("#input-id").attr('disabled', 'disabled');
        $("#input-id").fileinput('clear');
        $("#input-id").removeAttr('disabled');
    });

    $('#submitEdit').click(function () {
        if($("#edit").valid()){
            $.post(contextpath + "upload/modify", $("#edit").serialize(), function(){
                $.get(contextpath + "upload/get/product/" + $("#id").val(), function (data) {
                    appendImage(data, true);
                });

                swal("编辑图片成功", "", "success");
            })
            $('.close').click();
        }
    });

    if ($("#id").val() != ''){
        $.get(contextpath + "upload/get/product/" + $("#id").val(), function (data) {
            appendImage(data, true)
        });

        initFileInput();
    }
});